package net.vsame.url2sql.url.impl;

import java.util.Map;

import javax.servlet.ServletContext;

import net.vsame.url2sql.helper.CacheHelper;
import net.vsame.url2sql.helper.Url2SqlContext;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.url.Interceptor;
import net.vsame.url2sql.url.impl.UrlMapping.Chain;

import com.alibaba.fastjson.JSONObject;

public class CacheInterceptor implements Interceptor {
	
	public static CacheHelper cacheHelper;
	public static CacheHelper getCacheHelper() {
		return cacheHelper;
	}
	public static void setCacheHelper(CacheHelper cacheHelper) {
		CacheInterceptor.cacheHelper = cacheHelper;
	}

	@Override
	public void init(UrlMapping urlMapping, ServletContext servletContext) {
		
	}

	@Override
	public void invoke(Chain chain) {
		if(cacheHelper == null) {
			chain.next();
			return ;
		}
		
		long begin = System.currentTimeMillis();
		Url2SqlContext context = WebHelper.getContext();
		String key = cacheHelper.getCacheKey();
		if(key == null) {
			chain.next();
			return ;
		}
		
		JSONObject json = cacheHelper.getCache(key);
		if(json == null) {
			chain.next();
			cacheHelper.setCache(key);
		}else {
			Map<String, Object> d = context.getDatas();
			d.clear();
			d.putAll(json);
			d.put("$fromCache", cacheHelper.getCacheName());
		}
		
		//清除缓存
		cacheHelper.cleanCache();
		
		context.put("$time", System.currentTimeMillis() - begin);
	}

	@Override
	public void destroy() {
		
	}

}
